package com.kin207.netty.handle;

import java.io.PrintStream;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.kin207.netty.handle.impl.GroupAddMessageHandle;
import com.kin207.netty.handle.impl.GroupMessageHandle;
import com.kin207.netty.handle.impl.GroupRemoveMessageHandle;
import com.kin207.netty.handle.impl.HexMessageHandle;
import com.kin207.netty.handle.impl.P2pMessageHandle;
import com.kin207.netty.handle.impl.SetNameMessageHandle;
import com.kin207.netty.handle.impl.SystemMessageHandle;
import com.kin207.netty.msg.parse.FieldMessageParamIndex;
import com.kin207.netty.msg.parse.FieldMessageParamUtil;

public class MessageHandles {
	private static MessageHandles instance = null;
	
	private Map<String,IMessageHandle> handles = new LinkedHashMap<String, IMessageHandle>();
	
	public MessageHandles initDefault(){
		IMessageHandle handle = new SetNameMessageHandle();
		handles.put(handle.name(), handle);
		handle = new GroupAddMessageHandle();
		handles.put(handle.name(), handle);
		handle = new GroupRemoveMessageHandle();
		handles.put(handle.name(), handle);
		handle = new P2pMessageHandle();
		handles.put(handle.name(), handle);
		handle = new GroupMessageHandle();
		handles.put(handle.name(), handle);
		handle = new SystemMessageHandle();
		handles.put(handle.name(), handle);
		handle = new HexMessageHandle();
		handles.put(handle.name(), handle);
		return this;
	}
	
	public static MessageHandles newInstance(){
		if(instance==null){
			instance = new MessageHandles().initDefault();
		}
		return instance;
	}
	
	public static Map<String,IMessageHandle> handles(){
		return newInstance().getHandles();
		
	}
	
	public static void printHandles(){
		printHandles(MessageHandles.newInstance());
	}
	
	public static void printHandles(MessageHandles messageHandles){
		printHandles(messageHandles, System.out);
	}
	
	public static void printHandles(MessageHandles messageHandles, PrintStream out){
		if(messageHandles==null){
			return;
		}
		
		FieldMessageParamUtil paramUtil = new FieldMessageParamUtil();
		for(IMessageHandle item : messageHandles.handles.values()){
			Class pclass = item.paramClass();
			List<FieldMessageParamIndex> fields = paramUtil.getMessageParamFields(pclass);
			out.print(item.name());
			for(FieldMessageParamIndex param : fields){
				out.print(" {"+param.getField().getName()+"}");
			}
			out.println();
		}
	}
	
	public void addHandle(IMessageHandle messageHandle){
		handles.put(messageHandle.name(), messageHandle);
	}
	
	public void removeHandle(IMessageHandle messageHandle){
		handles.remove(messageHandle.name());
	}

	public Map<String, IMessageHandle> getHandles() {
		return handles;
	}

	public void setHandles(Map<String, IMessageHandle> handles) {
		this.handles = handles;
	}
	
}
